package com.ddddddl.zhangben.logic;

import java.util.ArrayList;
import java.util.HashMap;

import android.os.AsyncTask;

public abstract class BaseLogic implements Subject {
	
	private HashMap<Integer, ArrayList<Observer>> observers = new HashMap<Integer, ArrayList<Observer>>();
	
	@Override
	public void addListener(Observer observer, int event) {
		if (observers.get(event) == null) {
			observers.put(event, new ArrayList<Observer>());
		}
		observers.get(event).add(observer);
	}
	
	/**
	 * �ⲿ���ã���������Ҫ��װһ��{@link Request}��<br>
	 * ����������Ҫ���ش�������ôӦ����{@link Request}�д���{@link RequestListener}<p>
	 * ע�⣺�÷�����Ҫ�����̵߳���
	 * @param request
	 */
	public void sendRequest(Request request) {
		new RequestTask().execute(request);
	}
	
	/**
	 * ��������ľ������
	 * @param request
	 */
	protected abstract void handlerRequest(Request request);
	
	
	protected void notify(ExecuteMessage message) {
		ArrayList<Observer> observerList = observers.get(message.type);
		if (observerList != null && !observerList.isEmpty()) {
			for (Observer observer : observerList) {
				if (observer != null) {
					message.observer = observer;
					new NotifyTask().execute(message);
				}
			}
		}
	}
	
	private class RequestTask extends AsyncTask<Request, String, Request> {
		
		@Override
		protected Request doInBackground(Request... requests) {
			handlerRequest(requests[0]);
			return requests[0];
		}
		
		@Override
		protected void onPostExecute(Request request) {
			super.onPostExecute(request);
			RequestListener requestListener = request.requestListener;
			if (requestListener != null) {
				requestListener.onRequestFinished(request);
			}
		}
	}
	
	private static class NotifyTask extends AsyncTask<ExecuteMessage, String, ExecuteMessage> {

		@Override
		protected ExecuteMessage doInBackground(ExecuteMessage... messages) {
			return messages[0];
		}
		
		@Override
		protected void onPostExecute(ExecuteMessage message) {
			super.onPostExecute(message);
			message.observer.onNotify(message);
		}
		
	}
	
}
